package com.example.demofdfs.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;

import net.neoremind.sshxcute.core.ConnCredential;

public class XShell {

	private static JSch jsch = new JSch();
	private static Map<String, Session> sessionPool = new ConcurrentHashMap<>();
	
	public static void main(String[] args) throws JSchException, IOException {
		// TODO Auto-generated method stub
		String command = "ping 127.0.0.1";
		String host = "192.168.244.146";
		String username = "root";
		Session session = getSession(username, host);
		Channel channel = getChannel(session);
		InputStream in = exec(channel, command);
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		int len = 0;
		byte[] b = new byte[1024];
		StringBuffer sb = new StringBuffer();
//		while((len = in.read(b)) != -1) {
//			sb.append(new String(b, 0, len));
//			System.out.print(new String(b, 0, len));
//			sleep(100);
//		}
		
		new Thread(()->{
			sleep(5000);
			System.out.println(Thread.currentThread().getName());
			channel.disconnect();
		}).start();;
		
		String line = null;
		while((line = br.readLine()) != null) {
			System.out.println(line);
//			sleep(300);
		}
		
//		channel.disconnect();
		session.disconnect();
		
	}
	
	public static void sleep(long s) {
		try {
			Thread.sleep(s);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static Session getSession(String username, String host) throws JSchException {
		Session session = sessionPool.get(username + "@" + host);
		if (session == null) {
			session = jsch.getSession("root", "192.168.244.146", 22);
			sessionPool.put("root" + "@" + host, session);
			
			UserInfo ui = new ConnCredential("root");	
			session.setUserInfo(ui);
			session.connect();
		}
		return session;
	}
	
	private static Channel getChannel(Session session) {
		try {
			return session.openChannel("exec");
		} catch (JSchException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static InputStream exec(Channel channel, String command) throws JSchException, IOException {
		
		ChannelExec channelExec = (ChannelExec) channel;
		channelExec.setCommand(command);
		channelExec.setErrStream(System.err);
		channelExec.setOutputStream(System.out);
		channelExec.setInputStream(null);
		
		InputStream in = channelExec.getInputStream();
		channelExec.connect();

//		System.out.println(channelExec.isClosed());
//		channelExec.disconnect();
		return in;
	}

}
